package com.ase.数据结构.判断是否有环;

/**
 * @author gyhstart
 * @create 2021/2/28 - 21:27
 **/
public class isCycle {
    /**
     * 判断是否有环
     * @param head 链表头节点
     */
    public static int isCycle(Node head) {
        //环的长度
        int loopLength = 0;
        Node p1 = head;
        Node p2 = head;
        while (p2!=null && p2.next!=null){
            p1 = p1.next;
            p2 = p2.next.next;
            if(p1 == p2){
                System.out.println("node2 = " + p2.data);
                while (true){
                    p1 = p1.next;
                    p2 = p2.next.next;
                    loopLength++;
                    System.out.println("loopLength = " + loopLength);
                    if (p1 == p2){
                        return loopLength;
                    }
                }
            }
        }
        return 0;
    }


//    public static boolean isCycle(Node head) {
//        Node p1 = head;
//        Node p2 = head;
//        while (p2!=null && p2.next!=null){
//            p1 = p1.next;
//            p2 = p2.next.next;
//            if(p1 == p2){
//                System.out.println("p2 = " + p1.data);
//                return true;
//            }
//        }
//        return false;
//    }

    /**
     * 链表节点
     */
    private static class Node {
        int data;
        Node next;
        Node(int data) {
            this.data = data;
        }
    }

    public static void main(String[] args) throws Exception {
        Node node1 = new Node(5);
        Node node2 = new Node(3);
        Node node3 = new Node(7);
        Node node4 = new Node(2);
        Node node5 = new Node(6);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node3;
//
//        System.out.println(isCycle(node1));
        System.out.println("getLoopSize(node1,node1) = " + isCycle(node1));
    }
}
